import { ACategory } from "./ACategory";
import { IConfig } from "./IConfig";

export function Config(configTarget: { new() }) {
    return function (target) {
        ConfigInfos.push({ CateTarget: target, ConfigTarget: configTarget.prototype });
    }
}
const ConfigInfos: ConfigInfo[] = [];
type ConfigInfo = { CateTarget: any, ConfigTarget: any };

export class ConfigManager extends et.Entity {
    private static _Instance: ConfigManager;
    public static set Instance(value: ConfigManager) {
        this._Instance = value;
    }
    public static get Instance() {
        return this._Instance;
    }
    private allConfig:Map<any,ACategory> = new Map<any, ACategory>();
    public async init(){
        let propmiseAll=[];
        for (const ConfigInfo of ConfigInfos) {
            let cate=new ConfigInfo.CateTarget.constructor();
            this.allConfig.set(ConfigInfo.ConfigTarget,cate);
            propmiseAll.push(cate.init());
        }
        await Promise.all(propmiseAll);
    }
    public getOne<T extends IConfig>(type:{new():T}):T{
        let cate=this.allConfig.get(type);
        if(cate==null){
            return null;
        }
        let config=cate.getOne();
        return config as T;
    }
    public getAll<T extends IConfig>(type:{new():T}){
        let cate=this.allConfig.get(type);
        if(cate==null){
            return null;
        }
        let configs=cate.getAll();
        return configs as T[];
    }
    public get<T extends IConfig>(type:{new():T},id:any):T{
        let cate=this.allConfig.get(type);
        if(cate==null){
            return null;
        }
        let config=cate.get(id);
        return config as T;
    }
}
@et.objectSystem(ConfigManager)
class ConfigManagerAwakeSystem extends et.AwakeSystem<ConfigManager>{
    awake(self: ConfigManager): void {
        ConfigManager.Instance=self;
    }

}